package com.igoal.dao;

import java.util.HashSet;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.igoal.entity.DataStatus;
import com.igoal.entity.Hobby;
import com.igoal.entity.User;
import com.igoal.entity.factory.EntityFactory;
import com.igoal.utils.StringUtils;

@Repository("hobbyDAO")
public class HobbyDAOImp extends GenericDaoHibernate<Hobby, Long> implements
		HobbyDAO {

	public HobbyDAOImp() {
		super(Hobby.class);
	}

	public Hobby save(Hobby object) {
		getHibernateTemplate().saveOrUpdate(object);
		getHibernateTemplate().flush();
		return object;
	}

	public Hobby createHobby(User user, String name, String category) {
		if (getHobby(name, category) == null) {
			Hobby h = EntityFactory.createHobby(name, category);
			h.setUsers(new HashSet<User>());
			h.getUsers().add(user);
			return save(h);
		}
		return null;
	}

	public Hobby getHobby(String name, String category) {
		if (StringUtils.isBlank(name) || StringUtils.isBlank(category)) {
			return null;
		}

		DetachedCriteria dc = DetachedCriteria.forClass(Hobby.class);
		dc.add(Restrictions.eq("name", name));
		dc.add(Restrictions.eq("category", category));
		getByStatus(dc, DataStatus.USING);

		List<Hobby> result = findByCriteria(dc, 0, 1);
		if (result != null && result.size() > 0) {
			return result.get(0);
		}

		return null;
	}

}
